package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.AddressClient;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.OrderDTO;
import com.hmall.common.pojo.*;
import com.hmall.common.utils.SnowFlakeUtil;
import com.hmall.common.utils.UserUtil;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.service.IOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressClient addressClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 创建订单
     *
     * @param orderDTO
     */
    /*@Transactional(rollbackFor = Exception.class)*/
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void createOrder(OrderDTO orderDTO) {
        Order order = new Order();
        //todo 1.根据雪花算法生成订单id
        SnowFlakeUtil snowFlake = new SnowFlakeUtil(0);
        long orderId = snowFlake.nextId();
        //todo 2.商品微服务提供FeignClient，实现根据id查询商品的接口
        //todo 3.根据itemId查询商品信息
        Item item = itemClient.selectItem(orderDTO.getItemId());
        //todo 4.基于商品价格、购买数量计算商品总价：totalFee
        Long totalFee = item.getPrice() * orderDTO.getNum();
        //todo 5.封装Order对象，初识status为未支付
        order.setStatus(1);
        order.setId(orderId);
        order.setTotalFee(totalFee);
        order.setPaymentType(orderDTO.getPaymentType());
        Long userId = UserUtil.getParameter();
        order.setUserId(userId);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        //todo 6.将Order写入数据库tb_order表中
        orderMapper.insert(order);

        //todo 7.将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderId);
        orderDetail.setItemId(orderDTO.getItemId());
        orderDetail.setNum(orderDTO.getNum());
        orderDetail.setTitle(item.getName());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());
        orderDetail.setCreateTime(new Date());
        orderDetail.setUpdateTime(new Date());
        orderMapper.insertOrderDetail(orderDetail);

        //todo 8.将user-service的根据id查询地址接口封装为FeignClient
        //todo 9.根据addressId查询user-service服务，获取地址信息
        Address address = addressClient.findAddressById(orderDTO.getAddressId());
        // todo 10.将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(orderId);
        orderLogistics.setLogisticsNumber(null);
        orderLogistics.setLogisticsCompany(null);

        orderLogistics.setContact(address.getContact());
        orderLogistics.setPhone(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setTown(address.getTown());
        orderLogistics.setStreet(address.getStreet());
        orderLogistics.setCreateTime(new Date());
        orderLogistics.setUpdateTime(new Date());
        orderMapper.insertOrderLogistics(orderLogistics);

        //todo 11.在item-service提供减库存接口，并编写FeignClient
        //todo 12.减库存
        itemClient.subStock(orderDTO.getItemId(), orderDTO.getNum());
        //生产 消息者

        Message message = MessageBuilder
                .withBody(String.valueOf(orderId).getBytes(StandardCharsets.UTF_8))
                .setExpiration("5000")
                .build();
        // 消息ID，需要封装到CorrelationData中
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("ttl.direct", "ttl", message, correlationData);
    }
}
